let product=(function(){
	let cloumns=Array.from(document.querySelectorAll(".cloumn"));
	let allimg;
	let html=document.documentElement||document.body;
	let morebox=document.querySelector(".more");
	let data=null;
	//1.获取数据
	function getData(){
		let xhr=new XMLHttpRequest();
		xhr.open("GET","data.json",false);
		xhr.onreadystatechange=function(){
			if(xhr.readyState===4&&xhr.status===200){
				data=JSON.parse(xhr.response);
			}
		}
		xhr.send();
	}
	//2.循环渲染
	function render(){
		//console.log(data);
		//数据进行统一处理
		data=data.map(item=>{
			let {height,width}=item;
			item.width=230;
			item.height=230*height/width;
			return item;
		})
		
		let group;
		for(let i=0;i<data.length;i+=3){//0,3,6,9....
			group=data.slice(i,i+3);//i=0 (0,3) [0,1,2]
			//group [小中大] 排序
			group.sort((a,b)=>{return a.height-b.height});
			//console.log(group);
			cloumns.sort((a,b)=>{return b.offsetHeight-a.offsetHeight});
			//console.log(cloumns);
			
			group.forEach((item,index)=>{
				let {id,pic,height,width,title,link}=item;
				let str=`<div class="item">
					<a href="${link}">
						<div class="imgbox" style="height:${height}px">
							<img src="" alt="" data-src="${pic}" style="height:${height}px">
						</div>
						<p>${title}</p>
					</a>
				</div> `;
				
				cloumns[index].innerHTML+=str;
			})
		}
		
		allimg=Array.from(document.querySelectorAll("img"));
	}
	//监控50个盒子
	let oba=new IntersectionObserver(changes=>{
		//console.log(changes);//[{},{}...] 50个对象
		changes.forEach(change=>{
			if(change.isIntersecting){//加载图片
			   //target---你监控的目标对象box
			    let imgn=change.target.querySelector("img");
				//console.log(imgn);
				loadimg(imgn);//box
			}
		})
	},{
		threshold:[1]
	})
	function loadimg(img){
		let datasrc=img.getAttribute("data-src");
		let newimg=document.createElement("img");
		newimg.src=datasrc;
		newimg.onload=function(){
			img.src=datasrc;
			newimg=null;
			img.flag=true;
			let box=img.parentNode
			oba.unobserve(box);//取消监控
		}
	}
	//懒加载
	function handle(){
		allimg.forEach((img)=>{
			if(img.flag){
				 return;
			}
			let box=img.parentNode;
			oba.observe(box);//1.监控的是盒子
		})
	}
	//加载更多
	let count=0;
	function loadmore(){
	    let ob=new IntersectionObserver(changes=>{
			//console.log(changes);
			if(changes[0].isIntersecting){
				count++;
				if(count>3){
					morebox.innerHTML="已经加载完毕！";
					ob.unobserve(morebox);
					return;
				}
				getData();
				render();
				handle();
			}
		},{
			threshold:[0.5]
		})
		ob.observe(morebox);
	}
	return {
		init(){
			getData();
			render();
			handle();
			loadmore();
		}
	}
})()
product.init();